import DateUtils, {SecondString} from "./DateUtils";
import {URL} from "@/net/Api";
import NumUtils from "./NumUtils";
import mqtt_module from "mqtt/dist/mqtt"
import {StringBuffer} from "@/utils/StringUtils";
import ProtoParseUtils from "@/net/proto/ProtoParseUtil";

let mqttClient;

let options = {
    clientId: new StringBuffer().append('mqtt_web_').append(NumUtils.randomInt(100000, 999999))
        .append(DateUtils.dateToString(new Date(), SecondString)).toString()
};

export const Topic = {
    Statistics: "report/statistics",   //上报统计数据
    DevStatus: "report/device/status",//上报设备状态
    Exception: "report/exception",    //上报故障
    Command: "report/command",    //上报指令
    Message: 'message',
    Connect: 'connect',
    Reconnect: 'reconnect',
    Offline: 'offline',
    Close: 'close',
    Error: 'error',
};

export default class MqttUtils {

    /**
     * 封装mqtt的subscribe方法
     * @param topics
     * @constructor
     */
    static Subscribe(topics) {
        let client = createClient();
        client.subscribe(topics);
        client.on(Topic.Message, (topic, payload) => {
            console.log(topic, payload)
            ProtoParseUtils.getInstance().parseMqttMsg(topic, payload).then(result => {
                console.log(result)
            })
        });
    }

    /**
     * 添加topic
     * @param topics
     * @constructor
     */
    static AddTopic(topics) {
        let client = createClient();
        client.subscribe(topics);
    }

    /**
     * 移除topic
     * @param topics 要取消的topics
     * @constructor
     */
    static RemoveTopic(topics) {
        let client = createClient();
        client.unsubscribe(topics);
    }
}


/**
 * 创建单例模式的mqttClient
 * @returns {*}
 */
function createClient() {
    if (!mqttClient) {
        mqttClient = mqtt_module.connect(URL.DefaultMqttHost, options);
        console.log('Create mqtt client successful');
        mqttClient.on(Topic.Connect, () => {
            console.log('Connect the mqtt host of ' + URL.DefaultMqttHost + ' successful');
        });

        mqttClient.on(Topic.Reconnect, () => {
            console.log('mqtt reconnect')
        });

        mqttClient.on(Topic.Offline, () => {
            console.log('mqtt offline');
        });

        mqttClient.on(Topic.Close, () => {
            console.log('mqtt close');
            // window.location.reload(true);//调试阶段暂时注释掉
            // message.warning('MQTT服务异常，请重新刷新网页！', ToastTime.BigLong)
        });

        mqttClient.on(Topic.Error, () => {
            console.log('mqtt error')
        });
    }
    return mqttClient;
}

/**
 * 销毁mqtt client
 */
export function destroyMqttClient() {
    if (mqttClient) {
        mqttClient.end(true).then(() => {
            console.log('Mqtt client end');
        })
    }
}

